package com.gcu.drivingschool.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gcu.drivingschool.domain.dto.PageBean;
import com.gcu.drivingschool.domain.dto.UpdateBookExamDto;
import com.gcu.drivingschool.domain.po.BookExam;
import com.gcu.drivingschool.domain.po.Student;
import com.gcu.drivingschool.domain.vo.BookExamVo;
import com.gcu.drivingschool.domain.vo.Result;
import com.gcu.drivingschool.service.BookExamService;
import com.gcu.drivingschool.service.ScoreService;
import com.gcu.drivingschool.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 正式考试预约控制器
 *
 * @author zzr
 * @since 2024-05-17
 */
@RestController
@RequestMapping("/api/bookExams")
@RequiredArgsConstructor
@Tag(name = "正式考试预约控制器", description = "正式考试预约控制器")
public class BookExamController {
    private final BookExamService bookExamService;
    private final StudentService studentService;
    private final ScoreService scoreService;

    /**
     * 预约考试
     *
     * @param bookExam
     * @return
     */
    @Operation(summary = "预约考试", description = "预约考试（记录状态为待审核）")
    @PostMapping
    public Result bookExam(@RequestBody @Validated BookExam bookExam) {
        Student s = studentService.getById(bookExam.getStudentId());
        if (s == null) {
            return Result.fail("学员不存在");
        }
        if (s.getCoachId() == null) {
            return Result.fail("请先报名教练");
        }
        List<String> c = Arrays.asList("待审核", "审核通过");
        Long count = bookExamService.lambdaQuery().eq(BookExam::getStudentId, bookExam.getStudentId())
                .eq(BookExam::getSubject, bookExam.getSubject())
                .in(BookExam::getStatus, c)
                .count();
        if (count > 0) {
            return Result.fail("您已预约该门考试,请勿再次预约");
        }
        Long count1 = bookExamService.lambdaQuery().eq(BookExam::getStudentId, bookExam.getStudentId())
                .eq(BookExam::getSubject, bookExam.getSubject())
                .in(BookExam::getStatus, "考试通过")
                .count();
        if (count1 > 0) {
            return Result.fail("您已通过该门考试,请勿再次预约");
        }
        bookExam.setStatus("待审核");
        bookExamService.save(bookExam);
        return Result.success();
    }

    /**
     * 查询预约考试记录列表
     *
     * @param pageNum
     * @param pageSize
     * @param studentId
     * @param coachId
     * @param bookDate
     * @param status
     * @return
     */
    @Parameters({
            @Parameter(name = "pageNum", description = "第几页", in = ParameterIn.QUERY),
            @Parameter(name = "pageSize", description = "每页条数", in = ParameterIn.QUERY),
            @Parameter(name = "studentId", description = "学员id", in = ParameterIn.QUERY),
            @Parameter(name = "coachId", description = "教练id", in = ParameterIn.QUERY),
            @Parameter(name = "bookDate", description = "预约日期", in = ParameterIn.QUERY),
            @Parameter(name = "subject", description = "预约科目（科目一，科目二，科目三，科目四）", in = ParameterIn.QUERY),
            @Parameter(name = "status", description = "预约记录状态（待审核，审核通过，审核未通过，考试通过，考试未通过）", in = ParameterIn.QUERY)
    })
    @Operation(summary = "查询预约考试记录列表", description = "哪个参数不填代表所有")
    @GetMapping
    public Result getBookDrivingList(@RequestParam(required = false) Integer pageNum,
                                     @RequestParam(required = false) Integer pageSize,
                                     @RequestParam(required = false) Integer studentId,
                                     @RequestParam(required = false) Integer coachId,
                                     @RequestParam(required = false) String bookDate,
                                     @RequestParam(required = false) String subject,
                                     @RequestParam(required = false) String status) {
        //如果不传pageNum和pageSize,不分页
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = Integer.MAX_VALUE;
        }
        PageBean pb = new PageBean(0L, new ArrayList());
        LambdaQueryWrapper<BookExam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(studentId != null, BookExam::getStudentId, studentId)
                .eq(StringUtils.isNotBlank(status), BookExam::getStatus, status)
                .eq(StringUtils.isNotBlank(subject), BookExam::getSubject, subject);
        if (coachId != null) {
            //查询教练所有学员id
            List<Integer> sIds = studentService.lambdaQuery().eq(Student::getCoachId, coachId).list()
                    .stream().mapToInt(Student::getId).boxed().collect(Collectors.toList());
            if (sIds.size() > 0) {
                wrapper.in(BookExam::getStudentId, sIds);
            } else {
                return Result.success(pb);
            }
        }
        if (StringUtils.isNotBlank(bookDate)) {
            wrapper.eq(BookExam::getBookDate, LocalDate.parse(bookDate));
        }
        PageHelper.startPage(pageNum, pageSize);//分页
        //查询数据
        List<BookExam> list = bookExamService.list(wrapper);
        Page p = (Page) list;
        List<BookExam> r = p.getResult();
        List<BookExamVo> l = new ArrayList<>();
        //查询该记录学员详细信息（也可用联表查询）
        for (BookExam b : r) {
            Student student = studentService.getById(b.getStudentId());
            BookExamVo bookExamVo = new BookExamVo(b.getId(), student.getId(), student.getName(), student.getTelephone(),
                    b.getSubject(), b.getBookDate(), b.getStatus());
            l.add(bookExamVo);
        }
        pb = new PageBean(p.getTotal(), l);
        return Result.success(pb);
    }

    /**
     * 修改预约记录状态
     *
     * @param updateBookExamDto
     * @return
     */
    @Operation(summary = "预约审核", description = "由学员对应教练审核或录入成绩（修改状态）")
    @PutMapping
    public Result bookCheck(@RequestBody @Validated UpdateBookExamDto updateBookExamDto) {
        BookExam bookExam = new BookExam();
        bookExam.setId(updateBookExamDto.getId());
        bookExam.setStatus(updateBookExamDto.getStatus());
        boolean update = bookExamService.updateById(bookExam);
        if (!update) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 删除预约记录
     *
     * @param id
     * @return
     */
    @Parameter(name = "id", description = "预约记录id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "删除预约记录", description = "删除预约记录")
    @DeleteMapping("/{id}")
    public Result cancelBook(@PathVariable("id") Integer id) {
        boolean remove = bookExamService.removeById(id);
        if (!remove) {
            return Result.fail();
        }
        return Result.success();
    }
}
